package com.young.operation.interceptor;

import com.young.operation.config.DynamicDataSourceSelector;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class TenantInterceptor implements HandlerInterceptor {

    @Autowired
    DynamicDataSourceSelector dataSourceSelector;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 登录不会走这，如果有其他忽略的权限可以写在 WebMvcConfig
        String requestURI = request.getRequestURI();
        log.info("Request thread of {} uri is [{}]", Thread.currentThread().getId(), requestURI);
        String tenantId = request.getHeader("companyId");
        if (null == tenantId) {
            tenantId = request.getParameter("companyId");
        }
        if (null == tenantId) tenantId = "0";
        Long companyId = Long.parseLong(tenantId);
        return dataSourceSelector.setDataSource(companyId);
    }

}
